﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}

@model ERP.EquipmentManage.Dtos.EquipmentMaintenancePlanDto

@{
    ViewData["Title"] = Model != null ? "修改设备维护计划" : "新增设备维护计划";
    Layout = null;
    var isEdit = Model != null;
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>@ViewData["Title"]</title>
    <link href="~/layui/css/layui.css" rel="stylesheet" />
    <style>
        .layui-form-item .layui-input-inline {
            width: 200px;
        }
        .layui-card {
            margin: 15px;
        }
        .required-label {
            color: red;
        }
        .layui-input-group .layui-input-suffix {
            background: #f8f8f8;
            border-left: 1px solid #e6e6e6;
            width: 80px;
            text-align: center;
            line-height: 36px;
        }
        .auto-generate-checkbox {
            margin-left: 10px;
        }
        .layui-tab-content {
            padding: 15px 0;
        }
        .layui-card-body {
            padding-bottom: 20px;
        }
        .form-actions {
            padding: 20px 0;
            text-align: center;
            border-top: 1px solid #e6e6e6;
            margin-top: 20px;
        }
    </style>
</head>
<body>
    @Html.AntiForgeryToken()
    <div class="layui-fluid">
        <div class="layui-card">
            <div class="layui-card-header">
                <h3>@ViewData["Title"]</h3>
            </div>
            <div class="layui-card-body">
                <form class="layui-form" id="planForm" lay-filter="planForm">
                    <input type="hidden" name="id" value="@(Model?.Id ?? 0)">
                    
                    <!-- 基本信息 -->
                    <fieldset class="layui-elem-field layui-field-title">
                        <legend>基本信息</legend>
                    </fieldset>
                    
                    <div class="layui-row layui-col-space15">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">计划编码 <span class="required-label">*</span></label>
                                <div class="layui-input-block">
                                    <div class="layui-input-group">
                                        <input type="text" name="planCode" value="@(Model?.PlanCode ?? "")" 
                                               required lay-verify="required" placeholder="请输入计划编码" class="layui-input" readonly>
                                        @if (!isEdit)
                                        {
                                            <div class="layui-input-suffix">
                                                <input type="checkbox" id="autoGenerate" checked title="自动生成" lay-skin="primary" disabled>
                                            </div>
                                        }
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">计划名称 <span class="required-label">*</span></label>
                                <div class="layui-input-block">
                                    <input type="text" name="planName" value="@(Model?.PlanName ?? "")" 
                                           required lay-verify="required" placeholder="请输入计划名称(最多20字符)" class="layui-input">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="layui-row layui-col-space15">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">计划类型 <span class="required-label">*</span></label>
                                <div class="layui-input-block">
                                    <select name="planType" required lay-verify="required">
                                        <option value="">请选择计划类型</option>
                                        <option value="设备点检计划" @(Model?.PlanType == "设备点检计划" ? "selected" : "")>设备点检计划</option>
                                        <option value="设备保养计划" @(Model?.PlanType == "设备保养计划" ? "selected" : "")>设备保养计划</option>
                                        <option value="设备维修计划" @(Model?.PlanType == "设备维修计划" ? "selected" : "")>设备维修计划</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">执行频率 <span class="required-label">*</span></label>
                                <div class="layui-input-block">
                                    <div class="layui-input-group">
                                        <input type="number" name="frequency" value="@(Model?.Frequency ?? 1)" 
                                               required lay-verify="required|number" placeholder="请输入频率" class="layui-input" min="1">
                                        <div class="layui-input-suffix">
                                            <select name="frequencyUnit" required lay-verify="required">
                                                <option value="">单位</option>
                                                <option value="小时" @(Model?.FrequencyUnit == "小时" ? "selected" : "")>小时</option>
                                                <option value="天" @(Model?.FrequencyUnit == "天" ? "selected" : "")>天</option>
                                                <option value="周" @(Model?.FrequencyUnit == "周" ? "selected" : "")>周</option>
                                                <option value="月" @(Model?.FrequencyUnit == "月" ? "selected" : "")>月</option>
                                                <option value="季度" @(Model?.FrequencyUnit == "季度" ? "selected" : "")>季度</option>
                                                <option value="年" @(Model?.FrequencyUnit == "年" ? "selected" : "")>年</option>
                                            </select>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="layui-row layui-col-space15">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">创建时间</label>
                                <div class="layui-input-block">
                                    <input type="text" id="createdAt" name="createdAt" 
                                           value="@(Model?.CreatedAt.ToString("yyyy-MM-dd") ?? "")"
                                           placeholder="请选择创建时间" class="layui-input">
                                </div>
                            </div>
                        </div>
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">更新时间</label>
                                <div class="layui-input-block">
                                    <input type="text" id="updatedAt" name="updatedAt" 
                                           value="@(Model?.UpdatedAt.ToString("yyyy-MM-dd") ?? "")"
                                           placeholder="请选择更新时间" class="layui-input">
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="layui-row layui-col-space15">
                        <div class="layui-col-md6">
                            <div class="layui-form-item">
                                <label class="layui-form-label">状态</label>
                                <div class="layui-input-block">
                                    <select name="status">
                                        <option value="草稿" @(Model?.Status == "草稿" ? "selected" : "")>草稿</option>
                                        <option value="已确认" @(Model?.Status == "已确认" ? "selected" : "")>已确认</option>
                                        <option value="审批中" @(Model?.Status == "审批中" ? "selected" : "")>审批中</option>
                                        <option value="已审批" @(Model?.Status == "已审批" ? "selected" : "")>已审批</option>
                                        <option value="已完成" @(Model?.Status == "已完成" ? "selected" : "")>已完成</option>
                                        <option value="已拒绝" @(Model?.Status == "已拒绝" ? "selected" : "")>已拒绝</option>
                                        <option value="已生成生产工单" @(Model?.Status == "已生成生产工单" ? "selected" : "")>已生成生产工单</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">备注</label>
                        <div class="layui-input-block">
                            <textarea name="remark" placeholder="请输入备注(最多20字符)" class="layui-textarea">@(Model?.Remark ?? "")</textarea>
                        </div>
                    </div>
                </form>

                <!-- 设备点检项目清单（仅编辑模式显示） -->
                @if (isEdit)
                {
                    <fieldset class="layui-elem-field layui-field-title">
                        <legend>设备点检项目清单</legend>
                    </fieldset>
                    
                    <div class="layui-tab">
                        <ul class="layui-tab-title">
                            <li class="layui-this">设备清单</li>
                            <li>点检项目</li>
                        </ul>
                        <div class="layui-tab-content">
                            <div class="layui-tab-item layui-show">
                                <p style="text-align: center; color: #999; padding: 50px;">设备清单功能开发中...</p>
                            </div>
                            <div class="layui-tab-item">
                                <div style="margin-bottom: 10px;">
                                    <button type="button" class="layui-btn layui-btn-sm" id="addDvsubjectBtn">
                                        <i class="layui-icon">&#xe654;</i> 新增项目
                                    </button>
                                    <button type="button" class="layui-btn layui-btn-sm layui-btn-danger" id="deleteDvsubjectBtn">
                                        <i class="layui-icon">&#xe640;</i> 批量删除
                                    </button>
                                    <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" id="saveDvsubjectBtn">
                                        <i class="layui-icon">&#xe605;</i> 保存项目列表
                                    </button>
                                </div>
                                <table id="dvsubjectTable" lay-filter="dvsubjectTable"></table>
                            </div>
                        </div>
                    </div>
                }

                <!-- 操作按钮移到最下方 -->
                <div class="form-actions">
                    <button type="submit" class="layui-btn" lay-submit lay-filter="submitForm">
                        <i class="layui-icon">&#xe605;</i> 保存
                    </button>
                    <button type="button" class="layui-btn layui-btn-normal" id="cancelBtn">
                        <i class="layui-icon">&#xe603;</i> 返回
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="~/layui/layui.js"></script>
    <script>
        layui.use(['form', 'laydate', 'table', 'layer'], function () {
            var form = layui.form;
            var laydate = layui.laydate;
            var table = layui.table;
            var layer = layui.layer;
            var $ = layui.jquery;

            var isEdit = @(isEdit ? "true" : "false");
            
            // 检测只读模式
            var urlParams = new URLSearchParams(window.location.search);
            var isReadOnly = urlParams.get('readonly') === 'true';
            
            // 如果是只读模式，隐藏操作按钮并禁用表单
            if (isReadOnly) {
                // 修改页面标题
                $('.layui-card-header h3').text('查看设备维护计划（只读）');
                
                // 隐藏设备清单的操作按钮
                $('#addDvsubjectBtn').hide();
                $('#deleteDvsubjectBtn').hide();
                $('#saveDvsubjectBtn').hide();
                
                // 禁用所有表单元素
                $('#planForm input, #planForm select, #planForm textarea').attr('disabled', true);
                
                // 隐藏保存按钮，只显示返回按钮
                $('button[lay-submit]').hide();
            }

            // 初始化日期选择器
            laydate.render({
                elem: '#createdAt',
                type: 'date'
            });
            
            laydate.render({
                elem: '#updatedAt',
                type: 'date'
            });

            // 自动生成计划编码功能（仅新增模式）
            if (!isEdit) {
                // 初始生成编码
                generatePlanCode();
                
                // 监听自动生成复选框
                form.on('checkbox(autoGenerate)', function(data){
                    if (data.elem.checked) {
                        generatePlanCode();
                    } else {
                        $('input[name="planCode"]').val('');
                    }
                });
            }

            // 生成计划编码
            function generatePlanCode() {
                var now = new Date();
                var year = now.getFullYear();
                var month = String(now.getMonth() + 1).padStart(2, '0');
                var day = String(now.getDate()).padStart(2, '0');
                var hours = String(now.getHours()).padStart(2, '0');
                var minutes = String(now.getMinutes()).padStart(2, '0');
                var code = 'PLAN' + year + month + day + hours + minutes;
                $('input[name="planCode"]').val(code);
            }

            // 初始化设备点检项目表格（仅编辑模式）
            if (isEdit) {
                // 初始化表格缓存为空数组
                table.cache.dvsubjectTable = [];
                
                window.dvsubjectTableIns = table.render({
                    elem: '#dvsubjectTable',
                    page: true,
                    limits: [10, 20, 50],
                    limit: 10,
                    data: [], // 先设置为空数据
                    text: {
                        none: '暂无数据，请点击"新增项目"添加设备点检项目'
                    },
                    cols: [[
                        // 只读模式下不显示复选框
                        ...(isReadOnly ? [] : [{ type: 'checkbox', width: 50 }]),
                        { field: 'subcode', title: '项目编码', minWidth: 120 },
                        { field: 'subname', title: '项目名称', minWidth: 150 },
                        { field: 'subtype', title: '项目类型', minWidth: 120 },
                        { field: 'subcontext', title: '项目内容', minWidth: 200 },
                        { field: 'subarea', title: '标准', minWidth: 100 },
                        // 只读模式下不显示操作列
                        ...(isReadOnly ? [] : [{ title: '操作', width: 80, toolbar: '#dvsubjectOperationTpl', fixed: 'right' }])
                    ]],
                    response: {
                        statusName: 'code',
                        statusCode: 0,
                        msgName: 'msg',
                        countName: 'count',
                        dataName: 'data'
                    },
                    done: function(res, curr, count) {
                        console.log('PlanDvsubject表格渲染完成 - 总数:', count, '当前页:', curr);
                    }
                });

                // 单独加载数据库中的项目数据
                loadPlanDvsubjects($('input[name="planCode"]').val());
            } else {
                // 新增模式下也初始化表格缓存
                table.cache.dvsubjectTable = [];
            }

            // 加载计划的设备点检项目数据
            function loadPlanDvsubjects(planCode) {
                if (!planCode) {
                    console.log('计划编码为空，跳过加载项目数据');
                    return;
                }

                console.log('正在加载计划项目数据，计划编码:', planCode);
                $.ajax({
                    url: '/Equipment/GetPlanDvsubjectList',
                    type: 'POST',
                    data: { planCode: planCode, page: 1, limit: 1000 }, // 加载所有数据
                    success: function(res) {
                        console.log('加载计划项目数据响应:', res);
                        console.log('响应数据类型:', typeof res);
                        
                        if (res.code === 0 && res.data) {
                            console.log('数据项:', res.data);
                            console.log('数据项数量:', res.data.length);
                            
                            // 检查第一项数据的结构
                            if (res.data.length > 0) {
                                console.log('第一项数据结构:', res.data[0]);
                                console.log('第一项数据ID类型:', typeof res.data[0].Id, res.data[0].Id);
                                console.log('第一项数据所有属性:', Object.keys(res.data[0]));
                            }
                            
                            // 将数据库数据存储到缓存
                            var processedData = [];
                            res.data.forEach(function(item, index) {
                                console.log(`处理数据库项目 ${index}:`, item);
                                console.log(`数据库项目 ${index} 类型:`, typeof item);
                                console.log(`数据库项目 ${index} 构造函数:`, item.constructor?.name);
                                
                                // 强制转换为普通JavaScript对象，避免JsonElement问题
                                var processedItem = {
                                    Id: parseInt(item.Id || item.id || 0),
                                    subcode: String(item.subcode || item.Subcode || ''),
                                    subname: String(item.subname || item.Subname || ''),
                                    subtype: String(item.subtype || item.Subtype || ''),
                                    subcontext: String(item.subcontext || item.Subcontext || ''),
                                    subarea: String(item.subarea || item.Subarea || ''),
                                    tempId: Date.now() + Math.random() + index // 确保唯一性
                                };
                                
                                console.log(`处理后的项目 ${index}:`, processedItem);
                                console.log(`处理后ID类型:`, typeof processedItem.Id, processedItem.Id);
                                
                                processedData.push(processedItem);
                            });
                            
                            table.cache.dvsubjectTable = processedData;
                            console.log('最终缓存数据:', table.cache.dvsubjectTable);
                            
                            // 刷新表格显示
                            window.dvsubjectTableIns.reload({
                                data: table.cache.dvsubjectTable
                            });
                        } else {
                            console.log('没有找到计划项目数据或响应格式错误');
                            table.cache.dvsubjectTable = [];
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('加载计划项目数据失败:', error);
                        console.error('HTTP状态:', xhr.status);
                        console.error('响应文本:', xhr.responseText);
                        table.cache.dvsubjectTable = [];
                    }
                });
            }

            // 通用删除方法
            function deleteDvsubjectItems(ids, isMultiple) {
                var confirmText = isMultiple ? 
                    '确定要删除选中的 ' + ids.length + ' 个项目吗？' : 
                    '确定要删除该项目吗？';
                
                layer.confirm(confirmText, { icon: 3, title: '删除确认' }, function(index) {
                    // 从本地缓存中删除项目
                    if (table.cache.dvsubjectTable) {
                        // 根据ID或tempId删除项目
                        table.cache.dvsubjectTable = table.cache.dvsubjectTable.filter(function(item) {
                            return !ids.includes(item.Id) && !ids.includes(item.tempId);
                        });
                        
                        // 重新加载表格
                        window.dvsubjectTableIns.reload({
                            data: table.cache.dvsubjectTable
                        });
                        
                        layer.msg(isMultiple ? '批量删除成功' : '删除成功', { icon: 1 });
                    } else {
                        layer.msg('没有可删除的项目', { icon: 0 });
                    }
                    layer.close(index);
                });
            }

            // 监听表格工具条（仅编辑模式且非只读模式）
            if (isEdit && !isReadOnly) {
                table.on('tool(dvsubjectTable)', function (obj) {
                    var data = obj.data;
                    if (obj.event === 'delete') {
                        // 单个删除 - 使用tempId或Id
                        var deleteId = data.tempId || data.Id;
                        deleteDvsubjectItems([deleteId], false);
                    }
                });
            }

            // 监听表单提交（只读模式下不执行）
            if (!isReadOnly) {
            form.on('submit(submitForm)', function (data) {
                var formData = data.field;

                // 强制补全，防止layui未同步select值
                formData.planName = formData.planName || $('input[name="planName"]').val();
                formData.planType = formData.planType || $('select[name="planType"]').val();
                formData.frequencyUnit = formData.frequencyUnit || $('select[name="frequencyUnit"]').val();

                var id = parseInt(formData.id);
                // 调试输出
                console.log('formData.id:', formData.id, typeof formData.id);
                
                // 确保计划编码字段有值（因为readonly字段应该会被包含）
                if (!formData.planCode) {
                    formData.planCode = $('input[name="planCode"]').val();
                }
                
                // 构建DTO
                var submitData = {
                    planCode: formData.planCode,
                    planName: formData.planName,
                    planType: formData.planType,
                    frequency: parseInt(formData.frequency) || 1,
                    frequencyUnit: formData.frequencyUnit,
                    createdAt: formData.createdAt || new Date().toISOString(),
                    updatedAt: new Date().toISOString(),
                    status: formData.status || '草稿',
                    remark: formData.remark || ''
                };
                var url, requestData;
                if (id && id > 0) {
                    // 编辑
                    url = '/Equipment/UpdateMaintenancePlan';
                    requestData = { id: id, input: submitData };
                } else {
                    // 新增
                    url = '/Equipment/CreateMaintenancePlan';
                    requestData = submitData;
                }
                // 调试输出
                console.log('requestData:', requestData);
                $.ajax({
                    url: url,
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(requestData),
                    success: function (res) {
                        if (res.success) {
                            layer.msg(res.message, { icon: 1 }, function() {
                                window.location.href = '/Equipment/Index';
                            });
                        } else {
                            layer.msg('操作失败: ' + res.message, { icon: 2 });
                        }
                    },
                    error: function (xhr) {
                        layer.msg('服务器错误: ' + xhr.statusText, { icon: 2 });
                    }
                });
                return false;
            });
            }

            // 返回按钮
            $('#cancelBtn').on('click', function () {
                // 直接返回列表页面，不再显示确认对话框
                window.location.href = '/Equipment/Index';
            });
            
            // 保存项目列表按钮点击事件
            $('#saveDvsubjectBtn').on('click', function () {
                if (!table.cache.dvsubjectTable || table.cache.dvsubjectTable.length === 0) {
                    layer.msg('没有可保存的项目', { icon: 0 });
                    return;
                }
                
                var planCode = $('input[name="planCode"]').val();
                if (!planCode) {
                    layer.msg('计划编码不能为空', { icon: 2 });
                    return;
                }
                
                // 提取项目ID列表
                var dvsubjectIds = [];
                table.cache.dvsubjectTable.forEach(function(item) {
                    // 更安全的ID提取方式
                    var itemId = null;
                    if (item.Id !== null && item.Id !== undefined) {
                        itemId = item.Id;
                    } else if (item.id !== null && item.id !== undefined) {
                        itemId = item.id;
                    }
                    
                    if (itemId !== null && itemId !== undefined && !isNaN(itemId)) {
                        dvsubjectIds.push(parseInt(itemId));
                    }
                });
                
                if (dvsubjectIds.length === 0) {
                    layer.msg('没有有效的项目ID', { icon: 0 });
                    return;
                }
                
                // 调用保存函数
                savePlanDvsubjects(planCode, dvsubjectIds, function() {
                    layer.msg('项目列表保存成功', { icon: 1 });
                });
            });

            // 新增项目按钮点击事件
                $('#addDvsubjectBtn').on('click', function () {
                // 打开选择项目对话框
                openSelectDvsubjectDialog();
            });

            // 打开选择设备点检项目对话框
            function openSelectDvsubjectDialog() {
                var dialogContent = `
                    <div style="padding: 15px;">
                        <!-- 搜索表单 -->
                        <form class="layui-form" lay-filter="dvsubjectSearchForm" style="margin-bottom: 15px;">
                            <div class="layui-form-item">
                                <div class="layui-inline">
                                    <label class="layui-form-label" style="width: 60px;">编码</label>
                                    <div class="layui-input-inline" style="width: 120px;">
                                        <input type="text" name="subcode" placeholder="项目编码" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label" style="width: 60px;">名称</label>
                                    <div class="layui-input-inline" style="width: 120px;">
                                        <input type="text" name="subname" placeholder="项目名称" class="layui-input">
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <button type="button" class="layui-btn layui-btn-sm" lay-submit lay-filter="dvsubjectSearch">搜索</button>
                                    <button type="reset" class="layui-btn layui-btn-primary layui-btn-sm">重置</button>
                                </div>
                            </div>
                        </form>
                        <!-- 数据表格 -->
                        <table id="selectDvsubjectTable" lay-filter="selectDvsubjectTable"></table>
                    </div>
                `;

                var dialogIndex = layer.open({
                    type: 1,
                    title: '选择设备点检项目',
                    content: dialogContent,
                    area: ['900px', '600px'],
                    btn: ['确定', '取消'],
                    success: function(layero, index) {
                        // 重新渲染表单
                        form.render();
                        
                        // 初始化选择表格
                        var selectTableIns = table.render({
                            elem: '#selectDvsubjectTable',
                            url: '/Equipment/GetAvailableDvsubjectList', // 获取可选择的项目列表
                            method: 'POST',
                            page: true,
                            limits: [10, 20, 50],
                            limit: 10,
                            height: 400,
                            cols: [[
                                { type: 'checkbox', width: 50 },
                                { field: 'subcode', title: '项目编码', width: 120 },
                                { field: 'subname', title: '项目名称', width: 150 },
                                { field: 'subtype', title: '项目类型', width: 120 },
                                { field: 'subcontext', title: '项目内容', minWidth: 200 },
                                { field: 'subarea', title: '标准', width: 100 }
                            ]],
                            request: {
                                pageName: 'page',
                                limitName: 'limit'
                            },
                            response: {
                                statusName: 'code',
                                statusCode: 0,
                                msgName: 'msg',
                                countName: 'count',
                                dataName: 'data'
                            }
                        });

                        // 搜索功能
                        form.on('submit(dvsubjectSearch)', function(data) {
                            selectTableIns.reload({
                                where: data.field,
                                page: { curr: 1 }
                            });
                            return false;
                        });

                        // 存储表格实例以便确定按钮使用
                        window.currentSelectTableIns = selectTableIns;
                    },
                    btn1: function(index) {
                        // 确定按钮回调
                        var checkStatus = table.checkStatus('selectDvsubjectTable');
                        if (checkStatus.data.length === 0) {
                            layer.msg('请选择要添加的项目', { icon: 0 });
                            return false;
                        }

                        // 添加选中的项目到当前表格
                        addSelectedDvsubjects(checkStatus.data);
                        layer.close(index);
                        return false;
                    },
                    btn2: function(index) {
                        // 取消按钮回调
                        layer.close(index);
                    }
                });
            }

            // 添加选中的项目到当前表格
            function addSelectedDvsubjects(selectedData) {
                console.log('开始添加项目，选中数据:', selectedData);
                console.log('当前缓存数据:', table.cache.dvsubjectTable);
                
                var addedCount = 0;
                
                selectedData.forEach(function(item) {
                    // 检查是否已存在 - 使用id和subcode双重检查
                    var existingData = table.cache.dvsubjectTable || [];
                    var exists = existingData.some(function(existing) {
                        return existing.Id === item.Id || existing.subcode === item.subcode;
                    });

                    console.log('检查项目:', item.subcode, '是否存在:', exists);

                    if (!exists) {
                        // 直接添加到表格缓存数据中
                        if (!table.cache.dvsubjectTable) {
                            table.cache.dvsubjectTable = [];
                        }
                        
                        // 为新添加的项目保持原有的ID，同时添加临时ID用于删除操作
                        var newItem = {
                            Id: (item.Id !== null && item.Id !== undefined) ? parseInt(item.Id) : 
                                 (item.id !== null && item.id !== undefined) ? parseInt(item.id) : 0,
                            subcode: String(item.subcode || item.Subcode || ''),
                            subname: String(item.subname || item.Subname || ''),
                            subtype: String(item.subtype || item.Subtype || ''),
                            subcontext: String(item.subcontext || item.Subcontext || ''),
                            subarea: String(item.subarea || item.Subarea || ''),
                            tempId: Date.now() + Math.random() // 临时ID用于删除
                        };
                        
                        console.log('创建的新项目对象:', newItem);
                        console.log('新项目ID类型:', typeof newItem.Id, newItem.Id);
                        
                        table.cache.dvsubjectTable.push(newItem);
                        addedCount++;
                        console.log('添加项目成功:', newItem);
                    } else {
                        console.log('项目已存在，跳过:', item.subcode);
                    }
                });

                console.log('添加完成，共添加:', addedCount, '项目');
                console.log('最终缓存数据:', table.cache.dvsubjectTable);

                if (addedCount > 0) {
                    // 刷新表格显示
                    console.log('正在刷新表格...');
                    console.log('表格实例:', window.dvsubjectTableIns);
                    
                    if (window.dvsubjectTableIns) {
                        try {
                            window.dvsubjectTableIns.reload({
                                data: table.cache.dvsubjectTable
                            });
                            console.log('表格刷新成功');
                        } catch (error) {
                            console.error('表格刷新失败:', error);
                            // 尝试重新渲染表格
                            table.render({
                                elem: '#dvsubjectTable',
                                data: table.cache.dvsubjectTable,
                                page: true,
                                limits: [10, 20, 50],
                                limit: 10,
                                cols: [[
                                    ...(isReadOnly ? [] : [{ type: 'checkbox', width: 50 }]),
                                    { field: 'subcode', title: '项目编码', minWidth: 120 },
                                    { field: 'subname', title: '项目名称', minWidth: 150 },
                                    { field: 'subtype', title: '项目类型', minWidth: 120 },
                                    { field: 'subcontext', title: '项目内容', minWidth: 200 },
                                    { field: 'subarea', title: '标准', minWidth: 100 },
                                    ...(isReadOnly ? [] : [{ title: '操作', width: 80, toolbar: '#dvsubjectOperationTpl', fixed: 'right' }])
                                ]]
                            });
                        }
                    } else {
                        console.error('表格实例不存在，尝试重新创建');
                        // 如果表格实例不存在，创建新的
                        window.dvsubjectTableIns = table.render({
                            elem: '#dvsubjectTable',
                            data: table.cache.dvsubjectTable,
                            page: true,
                            limits: [10, 20, 50],
                            limit: 10,
                            cols: [[
                                ...(isReadOnly ? [] : [{ type: 'checkbox', width: 50 }]),
                                { field: 'subcode', title: '项目编码', minWidth: 120 },
                                { field: 'subname', title: '项目名称', minWidth: 150 },
                                { field: 'subtype', title: '项目类型', minWidth: 120 },
                                { field: 'subcontext', title: '项目内容', minWidth: 200 },
                                { field: 'subarea', title: '标准', minWidth: 100 },
                                ...(isReadOnly ? [] : [{ title: '操作', width: 80, toolbar: '#dvsubjectOperationTpl', fixed: 'right' }])
                            ]]
                        });
                    }
                    
                    layer.msg('添加成功，共添加 ' + addedCount + ' 个项目', { icon: 1 });
                } else {
                    layer.msg('所选项目已存在或没有可添加的项目', { icon: 0 });
                }
            }

            // 保存计划项目列表到数据库
            function savePlanDvsubjects(planCode, dvsubjectIds, callback) {
                console.log('开始保存计划项目列表');
                console.log('计划编码:', planCode);
                console.log('项目ID列表:', dvsubjectIds);
                console.log('项目ID列表类型:', typeof dvsubjectIds);
                console.log('项目ID列表长度:', dvsubjectIds.length);
                
                // 确保所有ID都是有效的数字
                var validIds = dvsubjectIds.filter(function(id) {
                    return id !== null && id !== undefined && !isNaN(id);
                }).map(function(id) {
                    return parseInt(id);
                });
                
                console.log('过滤后的有效ID列表:', validIds);
                console.log('有效ID列表长度:', validIds.length);
                
                if (validIds.length === 0) {
                    console.warn('没有有效的项目ID，跳过保存');
                    if (callback) callback();
                    return;
                }
                
                var dvsubjectIdsJson = JSON.stringify(validIds);
                console.log('序列化后的JSON:', dvsubjectIdsJson);
                
                $.ajax({
                    url: '/Equipment/SavePlanDvsubjects',
                    type: 'POST',
                    data: {
                        planCode: planCode,
                        dvsubjectIdsJson: dvsubjectIdsJson,
                        __RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val()
                    },
                    success: function(res) {
                        console.log('保存项目列表响应:', res);
                        if (res.success) {
                            console.log('项目列表保存成功');
                            if (callback) callback();
                        } else {
                            console.error('保存项目列表失败:', res.message);
                            layer.msg('保存项目列表失败: ' + res.message, { icon: 2 });
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('保存项目列表请求失败');
                        console.error('HTTP状态:', xhr.status);
                        console.error('响应文本:', xhr.responseText);
                        console.error('错误:', error);
                        layer.msg('保存项目列表失败，请重试', { icon: 2 });
                    }
                });
            }

            // 批量删除按钮点击事件
                $('#deleteDvsubjectBtn').on('click', function () {
                    var checkStatus = table.checkStatus('dvsubjectTable');
                    if (checkStatus.data.length === 0) {
                        layer.msg('请选择要删除的项目', { icon: 0 });
                        return;
                    }
                
                // 获取选中项目的ID - 使用tempId或id
                var ids = checkStatus.data.map(function(item) {
                    return item.tempId || item.Id;
                });
                
                // 调用通用删除方法
                deleteDvsubjectItems(ids, true);
            });
        });
    </script>

    <!-- 操作列模板 -->
    <script type="text/html" id="dvsubjectOperationTpl">
        <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="delete">删除</a>
    </script>
</body>
</html>
